<template>
  <view class="post-create-container">
    <!-- 头部导航 -->
    
    <view class="content-box">
      <input 
        v-model="form.title" 
        placeholder="你想说的标题..." 
      /></textarea>
    </view>
    <!-- 内容编辑区 -->
    <view class="content-box">
      <textarea 
        class="content-input" 
        v-model="form.content" 
        placeholder="写下你想说的话..." 
        maxlength="500"
        auto-height
      ></textarea>
      <view class="count">{{ form.content.length }}/500</view>
    </view>
	<!-- 话题输入 -->
	<view class="content-box" v-if="false"> 
	  <view class="topic-input-container">
		
		<input 
		  v-model="form.title" 
		  placeholder="#添加话题(如#今天的夕阳)" 
		  class="topic-input"
		  @input="handleTopicInput"
		/>
		<view class="topic-tags" v-if="form.topic">
		  <view class="topic-tag" v-for="(tag, index) in extractedTopics" :key="index">
			{{ tag }}
			<uni-icons 
			  type="plusempty" 
			  size="16" 
			  color="#999" 
			  @click="removeTopic(index)"
			></uni-icons>
		  </view>
		</view>
	  </view>
	</view>
    
    <!-- 媒体上传区 -->
    <view class="media-uploader">
      <view class="upload-tips">添加图片或视频（最多9个）</view>
      
      <view class="media-list">
        <!-- 已上传的媒体项 -->
        <view 
          class="media-item" 
          v-for="(item, index) in mediaList" 
          :key="index"
        >
          <image 
            v-if="item.type === 'image'" 
            class="media-preview" 
            :src="item.url" 
            mode="aspectFill"
          ></image>
          <video 
            v-if="item.type === 'video'" 
            class="media-preview" 
            :src="item.url" 
			:show-bottom-progress="false"
			:show-center-play-btn="false"
			:show-fullscreen-btn="false"
            controls
          ></video>
          <view class="delete-btn" @click="removeMedia(index)">
            <uni-icons type="closeempty" size="18" color="#fff"></uni-icons>
          </view>
        </view>
        
        <!-- 上传按钮 -->
        <view 
          class="upload-btn" 
          v-if="mediaList.length < 9"
          @click="showMediaPicker"
        >
          <uni-icons type="plusempty" size="32" color="#999"></uni-icons>
        </view>
      </view>
    </view>
    
    <!-- 分类选择 -->
    <view class="category-selector">
      <view class="section-title">选择分类</view>
      <view class="category-list">
        <view 
          class="category-item" 
          v-for="category in categories" 
          :key="category.id"
          :class="{ active: selectedCategory === category.id }"
          @click="selectCategory(category.id,category.name)"
        >
          {{ category.name }}
        </view>
      </view>
    </view>
    
    
    <!-- 媒体选择器 -->
    <u-popup :show="mediaPicker" @close="mediaPicker = false" :round="20" ref="mediaPicker" mode="bottom">
      <view class="media-picker-popup">
        <view class="popup-title">选择媒体类型</view>
        <view class="popup-options">
          <view class="option-item" @click="chooseImage">
            <uni-icons type="image" size="24" color="#FF5A5F"></uni-icons>
            <text>图片</text>
          </view>
          <view class="option-item" @click="chooseVideo">
            <uni-icons type="videocam" size="24" color="#FF5A5F"></uni-icons>
            <text>视频</text>
          </view>
        </view>
        <view class="cancel-btn" @click="closeMediaPicker">取消</view>
      </view>
    </u-popup>
	<!-- 添加位置信息展示和选择按钮 -->
	  <!-- <view class="location-section">
	    <view class="section-title">位置信息</view>
	    <view class="location-info" v-if="location.name">
	      <uni-icons type="location-filled" size="20" color="#FF5A5F"></uni-icons>
	      <text class="location-text">{{ location.name }}</text>
	    </view>
	    <button 
	      class="location-btn" 
	      @click="chooseLocation"
	      size="mini"
	      type="default"
	    >
	      {{ location.name ? '重新选择位置' : '选择位置' }}
	    </button>
	  </view> -->
	  <button @click="handleSubmit" style="color: #fff;" class="submit-btn" >发布</button>
  </view>
</template>

<script>
	import QQMapWX  from '@/libs/qqmap-wx-jssdk.js'
export default {
  data() {
    return {
	  form:{
		  content:'',
		  // labelId:'',
		  // latitudeLongitude:'',//经纬度
	  },
      content: '', // 文本内容
      mediaList: [], // 媒体列表
      selectedCategory: null, // 选中的分类ID
      isAnonymous: false, // 是否匿名
      categories: [],
      uploading: false ,// 是否正在上传
	  qqmapsdk:null,
	  picUrl:[],
	  videoUrl:[],
	  mediaPicker:false,
	  extractedTopics: [], // 提取出来的话题标签
    }
  },
  onLoad() {
  	this.getlist()
	this.qqmapsdk = new QQMapWX({key: 'MCLBZ-NRD6Q-R4E5C-4TIMJ-IEXHV-AJFDF' });
  },
  methods: {
	  async getlist() {
	  	const res = await this.$api.get('/Confessions/category','',false)
	  	if(res.data.code === 200) {
	  		this.categories = res.data.data
	  	}
	  },
    // 返回上一页
    goBack() {
      uni.navigateBack()
    },
    // 处理话题输入
	handleTopicInput() {
	  // 自动提取话题标签（以#开头的内容）
	  const topicText = this.form.topic;
	  const topicRegex = /#[^\s#]+/g;
	  this.extractedTopics = topicText.match(topicRegex) || [];
	  
	  // 自动高亮话题
	  if (topicText.endsWith('#') || topicText.endsWith(' ')) {
		this.form.topic = topicText.trim() + ' ';
	  }
	},
	
	// 移除话题标签
	removeTopic(index) {
	  this.extractedTopics.splice(index, 1);
	  // 更新输入框内容
	  this.form.topic = this.extractedTopics.join(' ') + ' ';
	},
    // 显示媒体选择器
    showMediaPicker() {
		this.mediaPicker = true
      // this.$refs.mediaPicker.open()
    },
    
    // 关闭媒体选择器
    closeMediaPicker() {
	  this.mediaPicker = false
      // this.$refs.mediaPicker.close()
    },
    
    // 选择图片
    chooseImage() {
	  uni.showLoading({title:'上传中...'})
      this.closeMediaPicker()
	  let that = this
      uni.chooseImage({
        count: 9 - this.mediaList.length, // 还能选择的数量
        sizeType: ['compressed'], // 压缩图
        sourceType: ['album', 'camera'], // 相册和相机
        success:  (res) => {
          // 添加到媒体列表
          res.tempFiles.forEach((file) => {
			  this.$api.uploadFile('/upload/File',file.path).then(respone => {
			    console.log('dasda',respone)
				uni.hideLoading()
				if(respone.code == 500) {
					uni.showToast({
						icon:'none',
						title:'图片内容违反规定，无法上传'
					})
					return 
					
				} 
				this.mediaList.push({
				  type: 'image',
				  url: respone.url,
				})
				that.picUrl.push(respone.url)
				
			  }).catch((err) => {
				  uni.hideLoading()
			  })
			
          })
        },
		fail: (err) => {
			uni.hideLoading()
		}
      })
    },
    
    // 选择视频
    chooseVideo() {
	  uni.showLoading({title:'上传中...'})
      this.closeMediaPicker()
	  let that = this
      uni.chooseVideo({
        sourceType: ['album', 'camera'],
        compressed: true,
        // maxDuration: 60, // 60秒
        success: (res) => {
          // 视频只能选一个，先清空已有的
          this.mediaList = this.mediaList.filter(item => item.type !== 'video')
		  this.$api.uploadFile('/upload/media',res.tempFilePath).then(response => {
		    uni.hideLoading()
			this.mediaList.push({
		      type: 'video',
		      url: response.data.url,
		      file: {
		        path: res.tempFilePath,
		        size: res.size,
		        duration: res.duration,
		        width: res.width,
		        height: res.height
		      }
		    })
			console.log('上传的图片地址',response)
			that.videoUrl = response.url
		  }).catch((err) => {
			  uni.hideLoading()
		  })
          // that.$api.uploadFile('/file/upload',res.tempFilePath,'videoUrl/').then((response) => {
          // 	console.log('上传的图片地址',response)
          // 	that.videoUrl = response.link
          // })
          
        },
		fail: (err) => {
			uni.hideLoading()
		}
      })
    },
    
    // 删除媒体
    removeMedia(index) {
      this.mediaList.splice(index, 1)
	  this.picUrl.splice(index,index)
	  this.videoUrl.splice(index,1)
    },
    
    // 选择分类
    selectCategory(id,name) {
      this.selectedCategory = id
	  this.form.category_id = id
	  this.form.category = name
    },
    
    // 切换匿名状态
    toggleAnonymous(e) {
      this.isAnonymous = e.detail.value.length > 0
    },
    
    // 提交发布
    async handleSubmit() {
      // 验证表单
      if (!this.validateForm()) return
      
      // 开始上传
      this.uploading = true
      
      try {
        // 上传媒体文件
        if(this.mediaList.length>0) this.form.images = JSON.stringify(this.mediaList)
        
        // 调用API提交数据
        const res = await this.submitPost(this.form)
        console.log('热水',res)
        // 发布成功
        uni.hideLoading()
        uni.showToast({ title: '发布成功', icon: 'success' })
        
        // 返回并刷新列表
        setTimeout(() => {
          uni.navigateBack()
          uni.$emit('post-created') // 通知列表刷新
        }, 1500)
        
      } catch (error) {
        uni.hideLoading()
        uni.showToast({ title: '发布失败: ' + error.message, icon: 'none' })
        this.uploading = false
      }
    },
    
    // 验证表单
    validateForm() {
		// if(!this.form.title.trim()) {
		// 	uni.showToast({ title: '请填写标题', icon: 'none' })
		// 	return false
		// }
      if (!this.form.content.trim() && this.mediaList.length === 0) {
        uni.showToast({ title: '请填写内容', icon: 'none' })
        return false
      }
      
      // if (!this.selectedCategory) {
      //   uni.showToast({ title: '请选择分类', icon: 'none' })
      //   return false
      // }
      
      return true
    },
    // 选择位置
        chooseLocation() {
          // 先检查授权状态
          uni.getSetting({
            success: (res) => {
              if (res.authSetting['scope.userLocation'] === false) {
                // 已拒绝过授权，提示用户手动开启
                uni.showModal({
                  title: '提示',
                  content: '您已拒绝位置授权，是否去设置页面打开？',
                  success: (res) => {
                    if (res.confirm) {
                      uni.openSetting()
                    }
                  }
                })
              } else {
                // 发起位置选择
                this.doChooseLocation()
              }
            }
          })
        },
		// 实际选择位置的方法
		doChooseLocation() {
		  uni.chooseLocation({
		    success: (res) => {
		      this.location = {
		        name: res.name,
		        address: res.address,
		        latitude: res.latitude,
		        longitude: res.longitude
		      }
		    },
		    fail: (err) => {
		      console.error('选择位置失败:', err)
		      this.handleLocationError(err)
		    }
		  })
		},
		// 统一处理定位错误
		handleLocationError(err) {
		  let errMsg = '选择位置失败'
		  
		  // 根据错误码提供更具体的提示
		  if (err.errMsg.includes('auth deny') || err.errMsg.includes('permission denied')) {
		    errMsg = '位置权限被拒绝，请在设置中打开'
		  } else if (err.errMsg.includes('system permission denied')) {
		    errMsg = '系统定位权限未开启，请检查手机设置'
		  } else if (err.errMsg.includes('location service unavailable')) {
		    errMsg = '定位服务不可用，请检查网络和GPS'
		  }
		  
		  uni.showModal({
		    title: '提示',
		    content: errMsg,
		    confirmText: '去设置',
		    success: (res) => {
		      if (res.confirm) {
		        // 打开系统设置或小程序设置
		        uni.openSetting()
		      }
		    }
		  })
		},
        // 获取当前位置
        getCurrentLocation() {
          uni.getLocation({
            type: 'gcj02', // 返回国测局坐标
            success: (res) => {
              this.location.latitude = res.latitude
              this.location.longitude = res.longitude
              
              // 获取位置名称
              this.getLocationName(res.latitude, res.longitude)
            },
            fail: (err) => {
              console.error('获取位置失败:', err)
              uni.showToast({
                title: '获取位置失败',
                icon: 'none'
              })
            }
          })
        },
        
        // 根据经纬度获取位置名称
        getLocationName(latitude, longitude) {
          // 使用微信小程序的地理位置接口
          wx.request({
            url: 'https://apis.map.qq.com/ws/geocoder/v1/',
            data: {
              location: `${latitude},${longitude}`,
              key: 'MCLBZ-NRD6Q-R4E5C-4TIMJ-IEXHV-AJFDF',
              get_poi: 0
            },
            success: (res) => {
              if (res.data.status === 0) {
                const result = res.data.result
                this.location.name = result.formatted_addresses.recommend || result.address
                this.location.address = result.address
              }
            },
            fail: (err) => {
              console.error('获取位置名称失败:', err)
            }
          })
        },
    
    
    // 提交帖子数据
    submitPost(postData) {
	  let that = this
      return new Promise((resolve, reject) => {
		that.$api.post('/Confessions/create',postData).then(res => {
			console.log('发布内容',res)
			if(res.data.code === 0) {
				resolve(res.data)
				
			} else {
			  reject(new Error(res.data.msg || '发布失败'))
			}
		})
      })
    }
  }
}
</script>

<style scoped>
	/* 话题输入框样式 */
	.topic-input-container {
	  width: 100%;
	}
	
	.topic-input {
	  width: 100%;
	  font-size: 28rpx;
	  padding: 20rpx 0;
	  color: #FF5A5F; /* 话题颜色 */
	}
	
	.topic-tags {
	  display: flex;
	  flex-wrap: wrap;
	  margin-top: 10rpx;
	}
	
	.topic-tag {
	  background-color: #FFEEEF;
	  color: #FF5A5F;
	  padding: 8rpx 20rpx;
	  border-radius: 30rpx;
	  font-size: 26rpx;
	  margin-right: 15rpx;
	  margin-bottom: 10rpx;
	  display: flex;
	  align-items: center;
	}
	
	.topic-tag uni-icons {
	  margin-left: 8rpx;
	}
	.location-section {
	  background-color: #fff;
	  border-radius: 16rpx;
	  padding: 30rpx;
	  margin-bottom: 30rpx;
	  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
	}
	
	.location-info {
	  display: flex;
	  align-items: center;
	  font-size: 28rpx;
	  color: #666;
	  margin: 20rpx 0;
	}
	
	.location-text {
	  margin-left: 10rpx;
	  flex: 1;
	}
	
	.location-btn {
	  width: 100%;
	  margin-top: 10rpx;
	  font-size: 28rpx;
	}
.post-create-container {
  padding: 20rpx 30rpx;
  background-color: #f8f8f8;
  min-height: 100vh;
}

/* 头部样式 */
.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx 0;
  margin-bottom: 30rpx;
}

.back-btn, .submit-btn {
  padding: 10rpx;
}

.title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.submit-btn {
  font-size: 32rpx;
  color: #FF5A5F;
}

/* 内容编辑区 */
.content-box {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.content-input {
  width: 100%;
  min-height: 200rpx;
  font-size: 32rpx;
  line-height: 1.6;
}

.count {
  text-align: right;
  font-size: 26rpx;
  color: #999;
  margin-top: 10rpx;
}

/* 媒体上传区 */
.media-uploader {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.upload-tips {
  font-size: 28rpx;
  color: #999;
  margin-bottom: 30rpx;
}

.media-list {
  display: flex;
  flex-wrap: wrap;
  margin: -10rpx;
}

.media-item, .upload-btn {
  width: 195rpx;
  height: 195rpx;
  margin: 10rpx;
  position: relative;
  border-radius: 12rpx;
  overflow: hidden;
  background-color: #f5f5f5;
}

.media-preview {
  width: 100%;
  height: 100%;
}

.delete-btn {
  position: absolute;
  right: 10rpx;
  top: 10rpx;
  width: 40rpx;
  height: 40rpx;
  border-radius: 50%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
}

.upload-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 190rpx;
  height: 190rpx;
  border: 2rpx dashed #ddd;
}

/* 分类选择 */
.category-selector {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  margin-bottom: 30rpx;
  color: #333;
}

.category-list {
  display: flex;
  flex-wrap: wrap;
  margin: -10rpx;
}

.category-item {
  padding: 16rpx 30rpx;
  margin: 10rpx;
  font-size: 28rpx;
  background-color: #f5f5f5;
  border-radius: 50rpx;
  color: #666;
}

.category-item.active {
  background-color: #FF5A5F;
  color: #fff;
}

/* 匿名选项 */
.anonymous-option {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.checkbox-label {
  display: flex;
  align-items: center;
  font-size: 30rpx;
  color: #333;
}

/* 媒体选择弹出层 */
.media-picker-popup {
  background-color: #fff;
  border-radius: 30rpx 30rpx 0 0;
  padding: 40rpx;
}

.popup-title {
  font-size: 32rpx;
  font-weight: bold;
  text-align: center;
  margin-bottom: 40rpx;
  color: #333;
}

.popup-options {
  display: flex;
  justify-content: space-around;
  margin-bottom: 40rpx;
}

.option-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  font-size: 28rpx;
  color: #333;
}

.option-item text {
  margin-top: 15rpx;
}

.cancel-btn {
  text-align: center;
  font-size: 32rpx;
  color: #FF5A5F;
  padding: 30rpx 0;
  border-top: 1rpx solid #eee;
}
</style>